import Vue from 'vue'
import Vuex from 'vuex'
import config from '@/config.js'
Vue.use(Vuex)

let lifeData = {};

try {
	// 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
	lifeData = uni.getStorageSync('lifeData');
} catch (e) {}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['vuex_userInfo', 'vuex_openid', 'vuex_token', 'vuex_phone', 'vuex_sysmbelInfo', "vuex_address"];

// 保存变量到本地存储中
const saveLifeData = function(key, value) {
	// 判断变量名是否在需要存储的数组中
	if (saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = uni.getStorageSync('lifeData');
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		uni.setStorageSync('lifeData', tmp);
	}
}
let timer = null
const store = new Vuex.Store({
	state: {
		/**
		 * 如果上面从本地获取的lifeData对象下有对应的属性，就赋值给state中对应的变量
		 * 加上vuex_前缀，是防止变量名冲突，也让人一目了然
		 */
		vuex_userInfo: lifeData.vuex_userInfo ? lifeData.vuex_userInfo : '',
		vuex_openid: lifeData.vuex_openid ? lifeData.vuex_openid : '',
		vuex_token: lifeData.vuex_token ? lifeData.vuex_token : '',
		vuex_phone: lifeData.vuex_phone ? lifeData.vuex_phone : '',
		vuex_sysmbelInfo: lifeData.vuex_sysmbelInfo ? lifeData.vuex_sysmbelInfo : '',
		vuex_address: lifeData.vuex_address ? lifeData.vuex_address : '',
		vuex_SPID: '',
		// 如果vuex_version无需保存到本地永久存储，无需lifeData.vuex_version方式
		vuex_version: '1.0.0',
		ws: null
	},
	mutations: {
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (nameArr.length >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveLifeData(saveKey, state[saveKey])
		},
		SETWS(state, value) {
			state.ws = value
		}
	},
	actions: {
		createConnect({
			commit,
			state,
			dispatch
		}) {
			if (state.ws) return;
			const ws = uni.connectSocket({
				url: 'wss://app.bangbaguan.com/ws?type=user',
				header: {
					'content-type': 'application/json',
					[config.TOKEN_NAME]: state.vuex_token
				},
				complete: (data) => {
					console.log(data);
				}
			});
			commit('SETWS', ws)

			ws.onOpen(() => {
				console.log('ws open...')
				dispatch('keepPing')
				if (timer) {
					clearInterval(timer);
					timer = null
				}
				timer = setInterval(() => {
					dispatch('keepPing')
				}, 10000)
			})
			ws.onMessage((msg) => {
				let data = JSON.parse(msg.data)
				if (data.type !== 'ping') {
					uni.$emit('pullmsg', data)
				}
			})
			ws.onClose((err) => {
				console.log('onclose:', err);
				if (timer) {
					clearInterval(timer)
					timer = null
					commit('SETWS', null)
					dispatch('createConnect')
				}
			})
			ws.onError((err) => {
				console.log('onerror:', err);
				if (timer) {
					clearInterval(timer)
					timer = null;
					commit('SETWS', null)
					dispatch('createConnect')
				}
			})

		},
		keepPing({
			state
		}) {
			state.ws.send({
				data: JSON.stringify({
					type: 'ping'
				}),
				success: () => {
					// console.log('ping');
				},
				fail: (err) => {
					console.log('pingf', err);
				}
			})
		},
		closeConnect({
			commit,
			state
		}) {
			if (state.ws) {
				console.log('close');
				clearInterval(timer)
				timer = null;
				state.ws.close({
					code: 1000
				})
				commit('SETWS', null)
			}
		},
		sendMessage({
			state
		}, data) {
			if (state.ws) {
				state.ws.send({
					data: JSON.stringify(data)
				})
			}
		}
	}
})

export default store